package com.anruisi.hxmes.auth.controller;

import com.anruisi.hxmes.auth.entity.Oauth2TokenDto;
import com.anruisi.hxmes.auth.util.RespResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
import java.util.Map;

/**
 * 自定义Oauth2获取令牌接口
 * @author cmy
 * @date 2021/5/20 13:11
 */
@RestController
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    TokenStore redisTokenStore;


    @Autowired
    private TokenEndpoint tokenEndpoint;

    /**
     * Oauth2登录认证
     */
    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public void postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        Oauth2TokenDto oauth2TokenDto = Oauth2TokenDto.builder()
                .token(oAuth2AccessToken.getValue())
                .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                .expiresIn(oAuth2AccessToken.getExpiresIn())
                .tokenHead("Bearer ").build();
        HttpServletResponse response =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        RespResult.success(response,"操作成功",oauth2TokenDto);
    }

    @DeleteMapping("/logout")
    public void logout(@RequestParam(name = "token") String accessToken, HttpServletResponse response){
        OAuth2AccessToken oAuth2AccessToken = redisTokenStore.readAccessToken(accessToken);
        if(oAuth2AccessToken != null){
            System.out.println("----access_token是："+oAuth2AccessToken.getValue());
            redisTokenStore.removeAccessToken(oAuth2AccessToken);
            OAuth2RefreshToken oAuth2RefreshToken = oAuth2AccessToken.getRefreshToken();
            redisTokenStore.removeRefreshToken(oAuth2RefreshToken);
            redisTokenStore.removeAccessTokenUsingRefreshToken(oAuth2RefreshToken);
        }
        RespResult.success(response,"登出成功");
    }

}
